#!/usr/bin/perl
#
use strict;
use warnings;
use Data::Dumper;
 
binmode STDOUT, ":utf8";
#use utf8;
 
use JSON;
require "doa_subs.pl";

use CGI;
use lib '.';
use users;

my ($username,$level) = &validate;
my ($realm) = get_realm();
my $q = new CGI;
print $q->header;
print $q->start_html('Alliance list');
print $q->h1('Alliance Member Locations');

############################## Main Prog ##############################
#
# This program will load the existing mapfile.json and allow users to query it
#
#

my $data;
my $outdata={};

my $player_id={};
my $player_name={};
my $player_count=loadPlayers($player_id,$player_name);
my $alliance_id={};
my $alliance_name={};
my $alliance_count=loadAlliance($alliance_id,$alliance_name);

$outdata=loadMAP("mapfile");
my $displayOPS="Y";

my %FORM;
foreach my $field ($q->param()) 
{
    $FORM{$field} = $q->param($field);
}
my $search=$FORM{search};
$displayOPS=$FORM{OPSdisplay} if exists $FORM{OPSdisplay};

chomp $search;
my $seachalli=$alliance_name->{$search}||"0";
if ( $seachalli eq "0" )
{
	print $q->p("Alliance not Found");
	print $q->br();
	print $q->a( {-href=>"listAlliance2.pl"}, "List Alliances");
	print $q->br();
	print $q->a( {-href=>"menu.cgi"}, "Main Menu");
	print $q->end_html;
	exit;
}

print $q->h2("Alliance $search");
		
my @pdata;
my $members=[];
$members=$outdata->{'members'}{$seachalli};
#print Dumper(@$members);
foreach my $pid (keys %{$members})
{
	my $city=$outdata->{'map'}{$pid}{'city'}{'name'}||"";
	my $loc=$outdata->{'map'}{$pid}{'city'}{'loc'}||"";
	my $clvl=$outdata->{'map'}{$pid}{'city'}{'level'}||"";
	my $cts=$outdata->{'map'}{$pid}{'city'}{'ts'}||"";
	my ($citydate,$citytime)=pdateTime($cts);
	my $might=$outdata->{'map'}{$pid}{'player'}{'might'}||"0";
	$might=numF($might);
	my $playerName=$player_id->{$pid}||$q->a({-href=>"/cgi-bin/addplayer2.pl?search=$pid&alli=$search"},$pid);
	my $tempstring=$q->td($playerName).$q->td($loc).$q->td($city).$q->td($clvl).$q->td( {-align=> "RIGHT"}, $might).$q->td($citydate." ".$citytime);
	push (@pdata, $tempstring);
	if ($displayOPS) 
	{
		my $outpostarray=$outdata->{'map'}{$pid}{'outposts'};
		foreach my $outpost (keys %{$outpostarray})
		{
			my $cityname=$outpost;
			my $maploc=$outpostarray->{$outpost}{'loc'};
			my $level=$outpostarray->{$outpost}{'lvl'};
			my $timestring=$outpostarray->{$outpost}{'ts'};
			my ($printdate,$printtime)=pdateTime($timestring);
			$tempstring=$q->td(" ").$q->td($maploc).$q->td($cityname).$q->td($level).$q->td(" ").$q->td($printdate." ".$printtime);
			push (@pdata, $tempstring);
		}
	}
}


print $q->table({-border=>undef,-width=>'100%'},
	$q->Tr({ -align => "CENTER", -valign => "TOP" },$q->th(['Player', 'Location', 'City', 'Level', 'Might', 'Last Updated'])),
	$q->Tr({ -align => "CENTER", -valign => "TOP" },\@pdata));

print $q->br();
print $q->a( {-href=>"listAlliance2.pl"}, "List Alliances");
print $q->br();
print $q->a( {-href=>"menu.cgi"}, "Main Menu");
print $q->end_html;
